package com.cjkj.consumables.service.impl;

import com.cjkj.common.constant.EquipmentConstant;
import com.cjkj.common.exception.ServiceException;
import com.cjkj.common.utils.DateUtils;
import com.cjkj.common.utils.SecurityUtils;
import com.cjkj.common.utils.StringUtils;
import com.cjkj.consumables.domain.TMedicalConsumablesInfo;
import com.cjkj.consumables.domain.dto.BatchOperateParam;
import com.cjkj.consumables.domain.dto.ConsumablesDistributionReq;
import com.cjkj.consumables.domain.dto.ListDataParam;
import com.cjkj.consumables.domain.vo.BatchOperateResult;
import com.cjkj.consumables.mapper.TMedicalConsumablesInfoMapper;
import com.cjkj.consumables.service.ITMedicalConsumablesInfoService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 耗材信息Service业务层处理
 * 
 * @author cjkj
 * @date 2025-10-11
 */
@Service
public class TMedicalConsumablesInfoServiceImpl implements ITMedicalConsumablesInfoService 
{
    @Resource
    private TMedicalConsumablesInfoMapper tMedicalConsumablesInfoMapper;

    /**
     * 查询耗材信息列表
     * 
     * @param params 耗材信息
     * @return 耗材信息
     */
    @Override
    public List<TMedicalConsumablesInfo> selectTMedicalConsumablesInfoList(ListDataParam params)
    {
        return tMedicalConsumablesInfoMapper.selectTMedicalConsumablesInfoList(params);
    }

    /**
     * 新增耗材信息
     * 
     * @param tMedicalConsumablesInfo 耗材信息
     * @return 结果
     */
    @Override
    public int insertTMedicalConsumablesInfo(TMedicalConsumablesInfo tMedicalConsumablesInfo)
    {
        TMedicalConsumablesInfo existInfo = tMedicalConsumablesInfoMapper.selectInfoBySerialNumber(tMedicalConsumablesInfo.getSerialNumber());
        if(existInfo != null) {
            throw new ServiceException("耗材编号已存在！");
        }

        Date nowDate = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        tMedicalConsumablesInfo.setCreateTime(nowDate);
        tMedicalConsumablesInfo.setCreateBy(username);
        tMedicalConsumablesInfo.setUpdateTime(nowDate);
        tMedicalConsumablesInfo.setUpdateBy(username);
        return tMedicalConsumablesInfoMapper.insertTMedicalConsumablesInfo(tMedicalConsumablesInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BatchOperateResult batchAddInfo(BatchOperateParam param) {
        // 耗材类型（1-体温传感器，2-心电电极贴）
        String type = getConsumablesType(param.getEquipmentType());
        // 生成所有编号
        List<String> serialNumberList = getSerialNumbers(type, param.getDate(), param.getStart(), param.getEnd());
        // 已存在的编号
        List<String> existList = tMedicalConsumablesInfoMapper.selectExistInfoBySerialNumbers(serialNumberList);
        // 筛选出需要添加的编号
        List<String> needAdd = serialNumberList.stream()
                .filter(e -> !existList.contains(e))
                .collect(Collectors.toList());
        // 批量添加新数据
        Date nowDate = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        List<TMedicalConsumablesInfo> infos = new ArrayList<>();
        for (String serialNumber : needAdd) {
            TMedicalConsumablesInfo info = new TMedicalConsumablesInfo();
            info.setEquipmentType(param.getEquipmentType());
            info.setSerialNumber(serialNumber);
            info.setCreateTime(nowDate);
            info.setCreateBy(username);
            info.setUpdateTime(nowDate);
            info.setUpdateBy(username);
            infos.add(info);
        }
        int success = tMedicalConsumablesInfoMapper.batchInsertTMedicalConsumablesInfo(infos);

        BatchOperateResult result = new BatchOperateResult();
        result.setSuccess(success);
        result.setExist(existList.size());
        result.setExistList(existList);
        return result;
    }

    /**
     * 批量删除耗材信息
     * 
     * @param ids 需要删除的耗材信息主键
     * @return 结果
     */
    @Override
    public int deleteTMedicalConsumablesInfoByIds(Long[] ids)
    {
        return tMedicalConsumablesInfoMapper.deleteTMedicalConsumablesInfoByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doDistribution(ConsumablesDistributionReq req) {
        String twId = req.getTwId();
        String xdId = req.getXdId();
        if(StringUtils.isBlank(twId) && StringUtils.isBlank(xdId)) {
            throw new ServiceException("请选择要分配的耗材！");
        }
        // 耗材ID
        List<String> consumablesIds = new ArrayList<>();
        // 体温传感器
        if(StringUtils.isNotBlank(twId)) {
            String[] twArr = twId.split(",");
            if(!ArrayUtils.isEmpty(twArr)) {
                ArrayList<String> strings = new ArrayList<>(Arrays.asList(twArr));
                consumablesIds.addAll(strings);
            }
        }
        // 心电电极贴
        if(StringUtils.isNotBlank(xdId)) {
            String[] xdArr = xdId.split(",");
            if(!ArrayUtils.isEmpty(xdArr)) {
                ArrayList<String> strings = new ArrayList<>(Arrays.asList(xdArr));
                consumablesIds.addAll(strings);
            }
        }
        // 批量分配
        int i = tMedicalConsumablesInfoMapper.batchSetDistributeInfoByIds(req.getAgentId(), consumablesIds);
        return i == consumablesIds.size() ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doRecovery(String[] ids) {
        int i = tMedicalConsumablesInfoMapper.batchClearDistributeInfoByIds(ids);
        return i == ids.length ? 1 : 0;
    }

    @Override
    public BatchOperateResult batchDistribution(BatchOperateParam param) {
        String agentId = param.getAgentId();
        if(StringUtils.isBlank(agentId)) {
            throw new ServiceException("请选择要分配的代理商！");
        }
        // 耗材类型（1-体温传感器，2-心电电极贴）
        String type = getConsumablesType(param.getEquipmentType());
        // 生成所有编号
        List<String> serialNumberList = getSerialNumbers(type, param.getDate(), param.getStart(), param.getEnd());
        // 查询可分配的编号
        List<String> list = tMedicalConsumablesInfoMapper.selectDistributableDataBySerialNumbers(serialNumberList);
        // 批量分配耗材
        int success = 0;
        if(! list.isEmpty()) {
            success = tMedicalConsumablesInfoMapper.batchSetDistributeInfo(agentId, list);
        }
        // 筛选出不能被分配的编号
        List<String> cannotDistribute = new ArrayList<>();
        if(serialNumberList.size() != list.size()) {
            cannotDistribute = serialNumberList.stream()
                    .filter(e -> !list.contains(e))
                    .collect(Collectors.toList());
        }
        // 返回结果
        BatchOperateResult result = new BatchOperateResult();
        result.setSuccess(success);
        result.setExist(cannotDistribute.size());
        result.setExistList(cannotDistribute);
        return result;
    }

    @Override
    public BatchOperateResult batchRecovery(BatchOperateParam param) {
        // 耗材类型（1-体温传感器，2-心电电极贴）
        String type = getConsumablesType(param.getEquipmentType());
        // 生成所有编号
        List<String> serialNumberList = getSerialNumbers(type, param.getDate(), param.getStart(), param.getEnd());
        // 查询可回收的编号
        List<String> list = tMedicalConsumablesInfoMapper.selectRecyclableDataBySerialNumbers(serialNumberList);
        // 批量回收耗材
        int success = 0;
        if(! list.isEmpty()) {
            success = tMedicalConsumablesInfoMapper.batchClearDistributeInfo(list);
        }
        // 筛选出不能被回收的编号
        List<String> cannotRecyclable = new ArrayList<>();
        if(serialNumberList.size() != list.size()) {
            cannotRecyclable = serialNumberList.stream()
                    .filter(e -> !list.contains(e))
                    .collect(Collectors.toList());
        }
        // 返回结果
        BatchOperateResult result = new BatchOperateResult();
        result.setSuccess(success);
        result.setExist(cannotRecyclable.size());
        result.setExistList(cannotRecyclable);
        return result;
    }

    /**
     * 获取耗材类型
     * @param typeCode
     */
    private String getConsumablesType(String typeCode){
        if("1".equals(typeCode)) {
            return EquipmentConstant.EQUIPMENT_TYPE_TJ02;
        }
        if("2".equals(typeCode)) {
            return EquipmentConstant.EQUIPMENT_TYPE_TJ03;
        }
        return "";
    }

    /**
     * 生成所有编号
     * @param type 耗材类型（1-体温传感器，2-心电电极贴）
     * @param date  日期
     * @param start 开始号
     * @param end  结束号
     */
    private List<String> getSerialNumbers(String type, Date date, int start, int end) {
        List<String> serialNumberList = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            serialNumberList.add(type + DateUtils.parseDateToStr("yyMMdd", date) + String.format("%04d", i));
        }
        return serialNumberList;
    }
}
